<template>
  <div class="login">
    <div class="left"></div>
    <div class="loginContainer">
      <h1 class="title">渣男管理系统</h1>
      <el-form
        :model="loginForm"
        status-icon
        :rules="rules"
        ref="loginForm"
        label-width="100px"
        class="demo-loginForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="text"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>
          <!-- 验证码 -->
          <el-form-item label="验证码" prop="captcha">
          <el-input
            class="captcha"
            type="text"
            v-model="loginForm.captcha"
            autocomplete="off"
          ></el-input>
          <span @click="refreshCaptcha" class="captcha-svg" v-html="captchaSvg">12345</span>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <video
      class="bg_video"
      muted
      src="../../assets/video/bg_video1.mp4"
      autoplay
      loop
      preload="auto"
    ></video>
  </div>
</template>
<script>
//登入逻辑的实现
//1.收集用户输入的username&password传递给后端

//2.登入通过后,将后端返回的token存到本地,跳转到主页
//3.每次请求的时候,携带token到请求头authorization

//4.展示token校验正确的数据

//5.校验不通过,跳转到登入页

import { login ,getCaptcha,verifyCaptcha,refreshCaptcha} from "@/api";
import { mapMutations } from "vuex";
export default {
  data() {
    // 校验用户名
    var validateUsername = (rule, value, callback) => {
      // 用户名正则，4到16位（字母，数字，下划线，减号）
      // var uPattern = /^[a-zA-Z0-9_-]{4,16}$/
      if (!value) {
        console.log(123);
        callback(new Error("请输入用户名4到16位"));
      } else {
        callback();
      }
    };
    // 校验用户密码
    var validatePassword = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };

    //校验验证码
     var validateCaptcha = (rule, value, callback) => {
      if (value === "" || value.length !==5) {
        callback(new Error("请输入验证码"));
      } else {
        callback();
      }
    };

    return {
      captchaSvg:"",
      loginForm: {
        username: "",
        password: "",
        captcha:""
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }]
      }
    };
  },
  mounted(){
   this.set_captcha()
   
  },
  methods: {
    //刷新验证码
    refreshCaptcha(){
       this.set_captcha()
    },
    //设置验证码
    set_captcha(){
      getCaptcha()
      .then(res => {
        this.captchaSvg = res.data.img;
        // console.log(res);
      })
    },
    ...mapMutations(["SET_USERINFO"]),
    submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          //代表本地校验通过

          //验证码验证是否正确
           let verifyRes = await  verifyCaptcha(this.loginForm.captcha)
           if (!verifyRes.data.state){
              //验证码不正确
              this.$message.error('验证码错误,请重新输入')
              return
           }
          //打开登入加载动画

          const loading = this.$loading({
            lock: true,
            text: "正在登入...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)"
          });

          let { username, password } = this.loginForm;
          //发送登入请求
          login(username, password)
            .then(res => {
              //服务器响应,关闭loading动画

              loading.close();

              if (res.data.state) {
                this.$message.success("登入成功");
                //用户名密码正确
                localStorage.setItem("wf-token", res.data.token);
                localStorage.setItem(
                  "wf-userInfo",
                  JSON.stringify(res.data.userInfo)
                );
                //更改vuex中state['userInfo']的值
                this.SET_USERINFO(res.data.userInfo);
                //跳转到主页
                this.$router.push("/");
              } else {
                //用户名或者密码错误
                this.$message.error("用户名密码错误");
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>
<style scoped lang="less">

.login {
  height: 100%;
  width: 100%;
  // background: url("");
  overflow: hidden;
}

.loginContainer {
  position: relative;
  z-index: 9;
  width: 25rem;
  height: 30.47619048rem;
  position: absolute;
  top: 50%;
  left: 75%;
  /* -webkit-transform: translate(-50%, -50%); */
  transform: translate(-50%, -50%);
  border-radius: 11px;
  background: rgba(83, 107, 182, 0.46);
  background: rgba(0, 0, 0, 0.2);
  text-align: center;
  .title {
    color: #fff;
    margin-top: 100px;
    margin-bottom: 50px;
  }
  .el-button.el-button--primary {
    width: 100%;
    background: linear-gradient(90deg, #1596fb, #002dff);
  }
  .bg_video {
    display: block;
    margin: auto;
    min-width: 100%;
    min-height: 100%;
    width: auto;
    height: auto;
    position: absolute;
    top: 0;
    left: 0;
    opacity: 0.5;
  }
}
.left {
  width: 50%;
  height: 100%;

  background-repeat: no-repeat;
  background-size: 50%;
  // float: left;
  position: absolute;
  opacity: 0.7;
  background-position: 60% 65%;
}
.el-form.demo-loginForm {
  padding: 0 50px 0 0;
}
</style>
